/**
 * Create by ray at 2015年6月4日 下午4:13:48.
 * Ray [email:rayinhangzhou@126.com]
 * TrackInterceptor.java is for :
 * TODO
 * Revision History
 * Date@Programmer: memo
 * ----------------------------------------------------------------
 * 2015年6月4日@Ray: initial
 **/
package com.souche.employment.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.souche.employment.CommonUtils;
import com.souche.employment.cache.RedisService;
import com.souche.employment.response.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class TrackInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        request.setAttribute("requestTime", System.currentTimeMillis());
        if (StringUtils.isNotBlank(AuthHolder.mail())) {
            String ip = CommonUtils.getIp(request);
            if (request.getMethod().equalsIgnoreCase(RequestMethod.POST.name()) && !redisService.setIfAbsent(request.getRequestURI() + AuthHolder.mail() + ip, "", 3)) {    // 3s内无法重复请求同个post接口，除非已返回响应
                throw CustomException.fail("您的请求太频繁了，请先歇一会儿~", null);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        String ip = CommonUtils.getIp(request);
        String uri = request.getRequestURI();
        long costTime = System.currentTimeMillis() - (Long) request.getAttribute("requestTime");
        String params = JSONObject.toJSONString(request.getParameterMap());
        if (StringUtils.isNotBlank(AuthHolder.mail())) {
            redisService.delete(request.getRequestURI() + AuthHolder.mail() + ip);
            log.info("{}{},{},{},{}__{}", (costTime > 3000 ? "slow-->" : ""), uri, params, AuthHolder.mail(), ip, costTime);
        } else {
            log.info("noLogin_{}{},{},{}__{}", (costTime > 3000 ? "slow-->" : ""), uri, params, ip, costTime);
        }
    }

}
